package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQuery;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 地区信息
 */
@RestController
@RequestMapping("regions")
public class RegionController {

    @Autowired
    private IRegionService regionService;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ServletContext servletContext;

    /**
     * 查询所有地区信息
     * @return
     */
    @GetMapping
    public List<Region> listAll(Integer state) {
        return regionService.listAll(state);
    }

    /**
     * 获取json的数据
     * @param qo
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/{regionId}/strategies",produces = "application/json;charset=utf-8")
    public PageInfo listStrategiesJson(StrategyQuery qo) throws Exception {
        //查询8条数据
        qo.setPageSize(8);
        return strategyService.query(qo);
    }

    /**
     * 获取html数据
     * @param qo
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/{regionId}/strategies",produces = "text/html;charset=utf-8")
    public void listStrategiesHtml(StrategyQuery qo, HttpServletResponse response) throws Exception {
        //获取全部攻略的数据
        qo.setPageSize(8);//分页查询
        PageInfo alls = strategyService.query(qo);
        //获取推荐的攻略数据集
        qo.setPageSize(0);//不分页
        qo.setState(Strategy.STATE_HOT);//推荐
        PageInfo commends = strategyService.query(qo);
        //使用FreeMarker合并模板和数据，需要传入FreeMarker的版本，不然显示方法为过时方法
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
        //设置模板目录所在的位置
        configuration.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("/template")));
        //获取模板文件
        Template template = configuration.getTemplate("strategyTemplate.ftl", "UTF-8");
        //创建map，将模板和数据放入map中
        HashMap<Object,Object> map = new HashMap<>();
        map.put("commends", commends);
        map.put("alls", alls);
        //合并数据1231
        template.process(map, response.getWriter());
    }
}
